<template>
  <div class="home">
    <!-- 1.导航栏 -->
    <div class="navigationBar">
      <div class="left">
        <div class="item">
          <div>
            <img src="@/assets/home/1.png" @click="router.push('/my-content')" />
          </div>
          <div>我的内容</div>
        </div>
        <div class="item">
          <div>
            <img src="@/assets/home/1.png" @click="gotoSharedContent()" />
          </div>
          <div>共享内容</div>
        </div>
        <div class="item">
          <div>
            <img src="@/assets/home/1.png" @click="router.push('/recycle')" />
          </div>
          <div>回收站</div>
        </div>
      </div>
      <div class="search">
        <el-input
          v-model="inputValue"
          class="w-50 m-2"
          placeholder="请输入瑞记文件名称"
          :prefix-icon="Search"
          @input="inputChange"
          :clearable="true"
        />
      </div>
    </div>
    <!-- 2. 头部 -->
    <div class="top">
      <b>
        <span
          style="font-size: 24px; font-family: SourceHanSansSC-medium; color: rgba(51, 51, 51, 1)"
        >
          最近
        </span>
      </b>
      <div>
        <el-dropdown popper-class="zdy_upload" placement="bottom-end">
          <el-button type="primary">
            上传<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="item in uploadOptions" :key="item.value" @click="uploadBtn">
                <div class="imgCont" style="margin-right: 10px">
                  <img src="@/assets/home/2.png" style="margin: 5px" />
                </div>
                <div class="cont">{{ item.label }}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <!-- 3.最近列表 -->
    <div class="tableBox">
      <div class="recentlyList">
        <!-- 3.2 列表-->
        <el-table
          :row-key="getRowKeys"
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#F5F9FC' }"
          @selection-change="selectionChange"
          ref="tableRef"
          v-loading="isLoading"
        >
          <el-table-column
            type="selection"
            prop="sec"
            label=""
            min-width="60"
            :reserve-selection="true"
          />
          <el-table-column prop="fileName" label="文件" min-width="509">
            <template #default="scope">
              <div class="fileContainer">
                <div class="fileImg" @click.prevent="goTodetailPage(scope.row)">
                  <img v-if="scope.row.picture" :src="scope.row.picture" class="img" />
                  <img v-else src="@/assets/home/3.png" class="defaultImg" />
                </div>
                <div class="fileInfo">
                  <!-- @keyup.enter="blur(scope.row)" -->
                  <div v-if="scope.row.isShowInput">
                    <el-input
                      v-model="renameValue"
                      @change="blur(scope.row)"
                      @blur="blur(scope.row)"
                      
                      placeholder="请输入标题"
                      clearable
                      maxlength="50"
                      ref="inputRef"
                    />
                  </div>
                  <div v-else>{{ scope.row.title }}</div>

                  <!-- 失败 -->
                  <div v-if="scope.row.transferFail==1">
                    <img src="@/assets/home/error.png" />
                    <span style="color: rgba(245, 34, 45, 1);">失败</span>
                  </div>
                  <!-- scope.row.transferFail==0  成功 / 待定-->
                  <template v-else>
                    <div v-if="scope.row.transferRate >= 100">
                      <span>{{ scope.row.totalTime }}</span>
                    </div>
                    <div v-else>
                      <img src="@/assets/home/4.png" />
                      <span style="color: rgba(255, 169, 64, 1);">转写中...{{ scope.row.transferRate }}%</span>
                    </div>
                  </template>

                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="不限归属" min-width="109" />
          <!-- createdTime -->
          <el-table-column prop="createdTime" label="最近创建/共享" min-width="209" />
          <el-table-column prop="opration" label="操作" min-width="120" fixed="right">
            <!-- scope.row   -->
            <template #default="scope">
              <el-button link type="primary" @click.prevent="edititem(scope.row)">
                重命名
              </el-button>
              <el-button
                class="deleteBtn"
                link
                type="primary"
                @click.prevent="deleteitem(scope.row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 4. 分页 -->
    <div class="pagination-block">
      <!-- 批量移除按钮 -->
      <el-button
        :class="['shiftBtn', selectRows.length > 0 ? 'active' : '']"
        @click="shiftBtns"
        type="danger"
        >移除</el-button
      >

      <!-- 分页 -->
      <div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="sizes,prev,  pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <div>页</div>
      </div>
    </div>

    <!-- 上传弹框 -->
    <el-dialog v-model="dialogFormVisible" title="上传音视频文件">
      <template #default>
        <!-- action:要上传的地址   :show-file-list是否展示上传列表 :on-change上传文件列表改变时 :auto-upload 是否自动上传 false为手动上传  :auto-upload="false" ,.webm,.flv,.f4v,.avi,.wmv,.mov-->
        <el-upload
          class="upload-demo"
          :auto-upload="false"
          drag
          multiple
          :show-file-list="false"
          :on-change="beforeAvatarUpload"
          :http-request="() => {}"
          :class="fileList.length > 0 ? 'isShowUpload' : ''"
          accept=".mp3,.mp4"
        >
          <img src="@/assets/home/5.png">
          <div class="el-upload__text">将文件拖拽至此区域 或 <em>选择文件上传</em></div>
          <template #tip>
            <div class="el-upload__tip">
              <!-- jpg/png files with a size less than 500kb -->
            </div>
          </template>
        </el-upload>
        <div v-if="fileList.length > 0" class="showFileList">
          <div class="top1">
            <div>已选文件: {{ fileList.length }}</div>
            <div class="tianjia">添加</div>
          </div>
          <div class="fileList">
            <el-scrollbar max-height="150px">
              <ul>
                <li v-for="(item, i) in fileList" :key="i">
                  <!-- 1.左侧 -->
                  <div>
                    <img src="@/assets/home/9.png" />
                    <div>
                      <div class="name">{{ item.name }}</div>
                      <div class="size">{{ (item.size / 1024 / 1024).toFixed(2) }} MB</div>
                    </div>
                  </div>
                  <div @click="deleteFileItem(item, i)">
                    <el-icon style="margin-right: 14px"><Close /></el-icon>
                  </div>
                </li>
              </ul>
            </el-scrollbar>
          </div>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelUpload()">取消</el-button>
          <!-- :disabled="fileList.length<=0" -->
          <el-button type="primary" @click="confirmUpload()" :disabled="fileList.length <= 0">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传中弹框 -->
    <div v-if="dialogUploadingVisible">
      <el-dialog
        v-model="dialogUploadingVisible"
        title="上传中"
        :modal="false"
        :align-center="false"
        class="dialoguploading"
      >
        <template #header>
          <div class="title">
            <!-- 1.已全部上传 -->
            <div v-if="alluploadFinished">已全部上传</div>

            <!-- 2.上传中，暂停 -->
            <template v-else>
              <div v-if="isContinues">上传中...{{ finishNum }}/{{ fileList.length }}</div>
              <div v-else>已全部暂停</div>
            </template>

            <div class="isFold" @click="isFold">
              <el-icon v-if="isFoldValue"><ArrowDown /></el-icon>
              <el-icon v-else><ArrowUp /></el-icon>
            </div>
          </div>
        </template>
        <template #default>
          <div class="showuploadingList" v-if="isFoldValue">
            <!-- 1.已全部上传 -->
            <div v-if="alluploadFinished" class="top2">
              <div>已上传 {{ fileList.length }}/{{ fileList.length }} 个文件</div>
            </div>

            <!-- 2.上传中，暂停 -->
            <template v-else>
              <div class="top2" v-if="isContinues">
                <div style="opacity: 1">{{ uploadSpeed ? uploadSpeed : 0 }}k/s</div>
                <div class="isPause" @click="pauseUploadingItems()">全部暂停</div>
              </div>
              <div class="top2" v-else>
                <div>已上传 0/{{ fileList.length }} 个文件</div>
                <div class="isPause" @click="continueUploadingItems()">继续</div>
              </div>
            </template>
            <div class="uploadingList">
              <el-scrollbar max-height="150px">
                <ul>
                  <li v-for="(item, i) in fileList" :key="i">
                    <!-- 1.左侧 -->
                    <div>
                      <img src="@/assets/home/9.png" />
                      <div>
                        <div class="name">{{ item.name }}</div>
                        <div class="size">{{ (item.size / 1024 / 1024).toFixed(2) }} MB</div>
                      </div>
                    </div>

                    <!-- 1 上传中 3暂停   4已完成  5失败-->
                    <div v-if="item.isuploadFinished == 4 || item.isuploadFinished == 5">
                      <!-- 成功 -->
                      <img
                        v-if="item.isuploadFinished == 4"
                        style="width: 20px; height: 20px; margin-right: 14px"
                        src="@/assets/home/success.png"
                      />
                      <!-- 失败 -->
                      <img
                        v-if="item.isuploadFinished == 5"
                        style="width: 20px; height: 20px; margin-right: 14px"
                        src="@/assets/home/error.png"
                      />
                    </div>
                    <!--2. 上传中/暂停  -->
                    <div class="pauseOrDelBtn" v-else>
                      
                      <!-- 暂停单个 -->
                      <img
                        v-if="item.isuploadFinished != 3"
                        style="margin-right: 14px"
                        src="@/assets/home/7.png"
                        @click.prevent="pauseUploadingItem(item, i)"
                      />
                      <!-- 继续单个 -->
                      <img
                        v-else
                        style="margin-right: 14px"
                        src="@/assets/home/8.png"
                        @click.prevent="continueUploadingItem(item, i)"
                      />
                      <!-- 取消 -->
                      <el-icon style="margin-right: 14px" @click.prevent="cancelFileItem(item, i)"
                        ><Close
                      /></el-icon>
                    </div>
                  </li>
                </ul>
              </el-scrollbar>
            </div>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { ref, onMounted, nextTick, computed, watchEffect, onBeforeUnmount } from 'vue'
// import { storeToRefs } from 'pinia'
// import { useApiAddressStore } from '@/pinia_stores/api_address_store.js'
import {
  ElMessage,
  ElMessageBox,
} from 'element-plus'
import { Search, UploadFilled, ArrowDown, Close } from '@element-plus/icons-vue'
const router = useRouter()
// import axios from 'axios'

import { request } from '@/utils/server.js'
// 引入MD5
import { MD5 } from 'crypto-js'

// 引入Minio
// import { Minio, initMinio, putObject } from 'vue3-minio'
// import { promises } from 'stream'
// import { rawListeners } from 'process'

// 获取组织信息，并传递给后端
const userId = ref(sessionStorage.getItem('userId') || '4600072255')
// const userId = ref(sessionStorage.getItem('userId') || '4233dfdf4')

const userName = ref('益伟康')
console.log(userId.value, userName.value)

// 0.---根据用户id,查询用户信息---
const getAuth = () => {
  request
    .post('/sweet-api/auth/query', {
      "userId": userId.value,
      
    })
    .then((res) => {
      // debugger
      // console.log("查询用户名成功",res.data);
      if (res.data.code == 1) {
        userName.value = res.data.data.name || '益伟康'
      } else {
        ElMessage({
          message: res.data.msg || '查询用户名失败',
          type: 'error'
        })
      }
    })
    .catch((error) => {
      console.log('查询用户名失败', error)
      ElMessage({
        message:error || '查询用户名失败',
        type: 'error'
      })
    })
}

// 1.----获取最近列表接口-----
const isLoading = ref(false)
const getRecentlyContentList = () => {
  // debugger
  isLoading.value = true
  request
    .get(
      '/sweet-api/mainpage/' +
        userId.value +
        '?current=' +
        currentPage.value +
        '&pageSize=' +
        pageSize.value
    )
    .then((res) => {
      // debugger
      // console.log("最近列表获取成功",res.data);
      if (res.data.code == 1) {
        // isLoading.value=false
        let list = res.data.data || []
        list.forEach((item) => {
          item.isShowInput = false
        })
        tableData.value = list

        // 总条数
        total.value = res.data.total
      }
    })
    .catch((error) => {
      console.log('最近列表获取失败', error)
    })
    .finally(() => {
      isLoading.value = false
    })
}
//  2.----移除最近列表接口-----
const tableRef = ref('')
const delateRecentlyItem = (ids) => {
  request
    .post('/sweet-api/mainpage/remove?ids=' + ids.join(','))
    .then((res) => {
      // debugger
      // console.log("移除最近列表成功",res.data);
      if (res.data.code == 1) {
        ElMessage({
          message: '移除成功',
          type: 'success'
        })

        //移除成功，重新调用展示列表
        getRecentlyContentList()

        selectRows.value = []
        // 清除勾选
        tableRef.value.clearSelection()
      } else {
        ElMessage({
          message: res.data.msg || '移除失败',
          type: 'error'
        })
      }
    })
    .catch((error) => {
      console.log('移除最近列表失败', error)
      ElMessage({
        message: error || '移除失败',
        type: 'error'
      })
    })
}

//3.----重命名接口----
const resetName = (row, value) => {
  // debugger
  request
    .post('/sweet-api/file/rename', {
      id: row.id,
      name: value
    })
    .then((res) => {
      //  debugger
      // console.log("重命名成功",res.data);
      if (res.data.code == 1) {
        // 隐藏输入框
        row.isShowInput = false
        ElMessage({
          message: '重命名成功',
          type: 'success'
        })

        //重命名成功，重新调用展示列表
        if (inputValue.value != '') {
          getSearchRequest()
        } else {
          getRecentlyContentList()
        }
      } else {
        ElMessage({
          message: res.data.msg || '重命名失败',
          type: 'error'
        })
      }
    })
    .catch((error) => {
      console.log('重命名失败', error)
      ElMessage({
        message: error || '重命名失败',
        type: 'error'
      })
    })
}

//  4.----获取minio 不分片密钥接口-----
const minioSecretKey = ref('')
const getKey = (md5, uploadFileName,i) => {
  request
    .post(
      '/sweet-api/oss/fetch/url',
      {
        userId: userId.value,
        userName: userName.value,
        md5: md5,
        title: uploadFileName,
      },
      {
        headers: {
          // 'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    )
    .then((res) => {
      // debugger
      if(res.data.code==1){
        console.log('获取minio密钥成功', res.data)
        minioSecretKey.value = res.data.data
        
        // 调用minio上传
        handleFiles(fileList.value[i], i,md5)
      }else{
        ElMessage({
          message: res.data.msg || '获取minio密钥失败',
          type: 'error'
        })
      }
      
    })
    .catch((error) => {
      console.log('获取minio密钥失败', error)
      ElMessage({
          message: error|| '获取minio密钥失败',
          type: 'error'
      })
    })
}

//  5.----获取minio 分片密钥接口-----

const getChunksKey = (md5, uploadFileName , i ,totalChunk ) => {
  request
    .post(
      '/sweet-api/oss/multipart/upload',
      {
        userId: userId.value,
        userName: userName.value,
        md5: md5,
        title: uploadFileName,
        "chunkSize": totalChunk ? totalChunk : ''
      },
      {
        headers: {
          // 'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
    )
    .then((res) => {
      if(res.data.code == 1){
        console.log('获取minio分片密钥成功', res.data)
        fileList.value[i].minioChunksSecretKey = res.data.data

        // 调用minio上传
        handleFiles(fileList.value[i], i,md5,totalChunk)
      }else{
         ElMessage({
          message: res.data.msg || '获取minio密钥失败',
          type: 'error'
        })
      }
      
    })
    .catch((error) => {
      console.log('获取minio分片密钥失败', error)
      ElMessage({
          message: error|| '获取minio密钥失败',
          type: 'error'
      })
    })
}

//6. ---分片上传完后合并接口---
const mergeChunks = (videoId,md5,index) => {
  
  // debugger
  request
    .get('/sweet-api/oss/multipart/complete/'+videoId)
    .then((res) => {
      // console.log("合并成功",res.data);
      if (res.data.code == 1) {
        //调用上传完成接口
        uploadFinish(videoId, md5,index)
        
        
      } 
    })
    .catch((error) => {
      console.log('合并失败', error)
      // 有一片上传失败，则整个文件上传失败
      fileList.value[index].isuploadFinished = 5
      
    })
}

//7.---上传完成接口---
// 全部上传完成的判断 isuploadFinished 1 上传中 3暂停   4已完成  5失败
const alluploadFinished = ref(false)
const uploadFinish = (videoId, md5,index) => {
  request
    .get('/sweet-api/oss/upload/finish/'+videoId + '?md5='+md5)
    .then((res) => {
      // console.log("上传完成",res.data);
      if (res.data.code == 1) {
        //  debugger
        // cancelfileList.value.forEach((item, i) => {
        //   if (item == res.data.data.title + '.' + res.data.data.fileName.split('.')[1]) {
        //     // 删除接口 待修改(item) indexOf(item)
        //   }
        // })
        //上传成功4
        fileList.value[index].isuploadFinished = 4
        //  debugger
        for (let i = 0; i < fileList.value.length; i++) {
          if (fileList.value[i].isuploadFinished != 4) {
            return
          }
        }
        // 所有的都上传完成
        alluploadFinished.value = true
        // 关闭上传中弹框
        // dialogUploadingVisible.value=false
      } else {
        //上传失败5
        fileList.value[index].isuploadFinished = 5
      }
    })
    .catch((error) => {
      //上传失败5
      fileList.value[index].isuploadFinished = 5

      console.log('上传失败', error)
    })
}
// 8.-----查询分片信息接口 isUpload 0否  1是
// {
//     "code": 1,
//     "data": {
//         "chunkSize": 5,
    //     "multipartList": [
    //         {
    //             "etag": "f46118947437059d15cf24e5f3935f16",
    //             "isUpload": 1,
    //             "partNumber": 1,
    //             "size": 10485952
    //         },
    //         {
    //             "etag": "c1e1dd271c89ab7420e6abaf6f14fdd6",
    //             "isUpload": 1,
    //             "partNumber": 2,
    //             "size": 20971860
    //         },
    //         {
    //             "etag": "5ee97f8256a5ee4aeb864d4c2361b7e0",
    //             "isUpload": 1,
    //             "partNumber": 3,
    //             "size": 31457768
    //         },
    //         {
    //             "etag": "9e16c4f3d789217ecfbd316fb6429eea",
    //             "isUpload": 1,
    //             "partNumber": 4,
    //             "size": 41943676
    //         },
    //         {
    //             "etag": "49bbdbd7553737ae67f562613248f4ff",
    //             "isUpload": 1,
    //             "partNumber": 5,
    //             "size": 47970397
    //         }
    //     ],
    //     "nextPartNumberMarker": 6,
    //     "partNumberMarker": 5,
    //     "uploadId": "ee6539f4-fd64-44db-b6e8-5d3fd4c81c07"
    // },

const getChunks = (videoId) => {
  return request
    .get(
      '/sweet-api/oss/multipart/status/'+videoId,
    )
    
}


// 8.----全局搜索接口----
const getSearchRequest = () => {
  request
    .get(
      '/sweet-api/conference/search?keyWord=' +
        inputValue.value +
        '&userId=' +
        userId.value +
        '&current=' +
        currentPage.value +
        '&pageSize=' +
        pageSize.value
    )
    .then((res) => {
      // debugger
      console.log('全局搜索成功', res.data)
      // fileList.value=res.data.data
      if (res.data.code == 1) {
        // isLoading.value=false
        let list = res.data.data || []
        list.forEach((item) => {
          item.isShowInput = false
        })
        tableData.value = list

        // 总条数
        total.value = res.data.total
      }
    })
    .catch((error) => {
      console.log('全局搜索失败', error)
    })
}


onMounted(() => {
  // 调用最近列表
  getRecentlyContentList()
  // 调用查询用户信息接口
  getAuth()

  // 轮询刷新
  setTimeoutZdy(option)
})

// 生命周期:销毁前
onBeforeUnmount(() => {
  // 退出页面 停止轮询
  option.isClose = true
})

//共享内容
const gotoSharedContent=()=>{
   ElMessage({
    message: '功能完善中...',
    type: 'warning',
  })
}

// 1.全局搜索
const inputValue = ref('')
function debounce(func, wait, immediate) {
  let timeout
  return function () {
    let context = this
    let args = arguments
    if (timeout) {
      clearTimeout(timeout)
    }
    if (immediate) {
      let callNow = !timeout
      timeout = setTimeout(() => {
        timeout = null
      }, wait)
      if (callNow) {
        typeof func === 'function' && func.apply(context, args)
      }
    } else {
      timeout = setTimeout(() => {
        typeof func === 'function' && func.apply(context, args)
      }, wait)
    }
  }
}
// 搜索框输入内容变化，搜索
const inputChangeFn = () => {
  console.log(inputValue.value)
  // debugger
  //发请求
  if (inputValue.value != '') {
    getSearchRequest()
  } else {
    getRecentlyContentList()
  }
}
const inputChange = debounce(inputChangeFn, 500, false)

// 2. 上传
const uploadValue = ref('')
const uploadOptions = ref([
  {
    value: 1,
    label: '上传本地文件'
  }
  // {
  //   value: 2,
  //   label: '上传云端文件',
  // }
])
const dialogFormVisible = ref(false)
// 主页-'上传本地文件'按钮
const uploadBtn = () => {
  fileList.value = []
  //展示上传弹框
  dialogFormVisible.value = true
}
// 选择上传的文件列表
const fileList = ref([])

const finishNum = computed(() => {
  let count = 0
  for (let i = 0; i < fileList.value.length; i++) {
    if (fileList.value[i].isuploadFinished == 4) {
      count++
    }
  }
  return count
})

const beforeAvatarUpload = (rawFile) => {
  console.log('0000000', rawFile)
  
  // debugger
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else
  // if (rawFile.size / 1024 / 1024 > 20) {
  //   ElMessage.error('上传文件不能超过 20MB!')
  //   return false
  // }

  for (var i = 0; i < fileList.value.length; i++) {
    if (rawFile.name == fileList.value[i].name) {
      ElMessage.error('上传文件名重复！')
      return
    }
  }

  fileList.value.push(rawFile)
  return true
}


// ------minio上传方法---------
const handleFiles = (f, index,md5,totalChunk) => {
  
  // return new Promise((resolve,reject)=>{
  let reader = new FileReader()
  reader.readAsArrayBuffer(f.raw)
  
  reader.onload =async function (e) {
    // let res = e.target.result //ArrayBuffer

    
    // 创建一个用于计算上传速率的变量
    f.startTime = new Date().getTime()
    f.uploadedBytes = 0
    f.uploadSpeed = 0
    
    if(f.raw.size<(10 * 1024 * 1024)){
      // debugger
      // 不分片
      let formData = minioSecretKey.value.formData
      formData['file'] = f.raw
      
      request
        .post(minioSecretKey.value.endPoint + '/' + minioSecretKey.value.bucket, formData, {
          signal: f.controller.signal,
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (e) => {
            let progressEvent = e.event

            if (progressEvent.lengthComputable) {
              const currentTime = new Date().getTime()

              //时间戳/1000 意思是毫秒转化为秒
              const elapsedTime = (currentTime - f.startTime) / 1000

              //progressEvent.loaded：已上传的字节数，单位为字节
              const uploaded = progressEvent.loaded - f.uploadedBytes

              // B/s 比特率 每秒的上传速率  字节/秒 --k/s
              f.uploadSpeed = (uploaded / elapsedTime / 1024 / 8).toFixed(0)

              // 更新已上传的字节数
              f.uploadedBytes = progressEvent.loaded
            }
          }
        })
        .then(function (response) {
          console.log(`${f.raw.name} 上传成功`, response)

          // 调用上传完成接口
          uploadFinish(minioSecretKey.value.videoId, md5,index)
        })
        .catch(function (error) {
          console.error(`${f.raw.name} 上传失败`, error)
        })
      }else{
        //分片
        let multipartList=f.minioChunksSecretKey.multipartList

        // 设置分片大小：10MB
        var chunkSize = 10 * 1024 * 1024
        // 数组存放所有分片
        var chunks = []
        // 遍历所有分片
        for (var j = 0; j < totalChunk; j++) {
          // 利用slice获取分片
          var start = j * chunkSize
          var end = Math.min(f.raw.size, start + chunkSize)
          // slice() 方法可从已有的数组中返回选定的元素
          var blob = f.raw.slice(start, end)
          //console.log("分片大小",blob)
          // 添加分片到数组
          chunks.push(blob)
        }
        
        let total=0
        // for(let i=0;i<multipartList.length;i++){
        for(let i=(f.nextPartNumberMarker?(f.nextPartNumberMarker-1):0);i<multipartList.length;i++){
          let formData = new FormData()
          formData.append("file",chunks[i])
          // console.log("总文件大小",f.raw.size)
         
          //console.log('start===============',i)
          await request
            // .put(multipartList[i].uploadUrl, formData, {
            .put(multipartList[i].uploadUrl, chunks[i], {
              signal: f.controller.signal,
              headers: {
                'Content-Type': "application/octet-stream"
              },
              onUploadProgress: (e) => {
                let progressEvent = e.event

                if (progressEvent.lengthComputable) {
                  const currentTime = new Date().getTime()

                  //时间戳/1000 意思是毫秒转化为秒
                  const elapsedTime = (currentTime - f.startTime) / 1000

                  //progressEvent.loaded：已上传的字节数，单位为字节
                  const uploaded = progressEvent.loaded - f.uploadedBytes

                  // B/s 比特率 每秒的上传速率  字节/秒 --k/s
                  f.uploadSpeed = (uploaded / elapsedTime / 1024 / 8).toFixed(0)

                  // 更新已上传的字节数
                  f.uploadedBytes = progressEvent.loaded
                }
              }
            })
            // .then((response)=>{
               // console.log('end===============',i)
                if(i== (multipartList.length-1)){
              
                  // debugger
                  //分片上传完成 调用合并接口
                  mergeChunks(f.minioChunksSecretKey.videoId , md5,index)
                }else{
                  // fileList.value[index].isuploadFinished=5
                }
                
            // })
            // .catch((error)=>{
              // console.log(error)
                // fileList.value[index].isuploadFinished=5
            // })
            
        }
        
      }
  }
  // })
}

// 2.1 速率计算
const uploadSpeed = ref(0)
const getuploadSpeed = () => {
  let total = 0

  for (let i = 0; i < fileList.value.length; i++) {
    // console.log('888888888888', fileList.value[i])
    if (fileList.value[i].uploadSpeed) {
      total += fileList.value[i].uploadSpeed
    }
  }
  return total / fileList.value.length
}
watchEffect(() => {
  uploadSpeed.value = getuploadSpeed()
})

// 2.1 删除已选择的上传文件
const deleteFileItem = (file, i) => {
  //  debugger
  fileList.value.splice(i, 1)

}

// 取消上传按钮
const cancelUpload = () => {
  dialogFormVisible.value = false
  fileList.value = []
}
// 2.2 上传弹框中 确定上传按钮
const confirmUpload = () => {
  // debugger
  dialogFormVisible.value = false

  // 调用获取minio密钥接口
  for (let i = 0; i < fileList.value.length; i++) {
    fileList.value[i].isuploadFinished = 1
    
    const encryptedString = MD5(fileList.value[i].name + fileList.value[i].size).toString()
    fileList.value[i].md5=encryptedString

    const controller = new AbortController()
    // debugger
    fileList.value[i].controller = controller

    if(fileList.value[i].size < (10*1024*1024)){ 
      
      // 调用获取minio 不分片密钥接口 
      getKey(encryptedString, fileList.value[i].name,i)

    }else{
      // debugger
      //分片
      // 获取文件
      var file = fileList.value[i].raw
      // debugger
      // 设置分片大小：10MB
      var chunkSize = 10 * 1024 * 1024
      // 计算总共有多少个分片
      var totalChunk = Math.ceil(file.size / chunkSize)
      fileList.value[i].totalChunk=totalChunk
      
      // 调用获取minio 分片密钥接口 
      getChunksKey(encryptedString, fileList.value[i].name,i,totalChunk) 
      
    }
 
  }


  // 打开上传中弹框
  dialogUploadingVisible.value = true

  // 折叠按钮默认打开
  isFoldValue.value = true
}

// 2.3 上传中弹框
const dialogUploadingVisible = ref(false)

// 用于判断是显示全部暂停 还是 继续(默认继续)
const isContinues = ref(true)

//2.4 暂停上传文件----
const pauseUploadingItem = (file, i) => {
  fileList.value[i].isuploadFinished = 3
  
  //2.发请求
  //调用取消上传请求
  // debugger
  fileList.value[i].controller.abort()
  //1.弹框确认
  // debugger 
  

  let count=0
  // 如果所有的都暂停了,则 展示 继续
  for (let j = 0; j < fileList.value.length; j++) {
    if (fileList.value[j].isuploadFinished == 3) {
      count++
    }
    
  }
  if(count==fileList.value.length){
    isContinues.value = false
  }
  
}
// 2 全部暂停
const pauseUploadingItems = () => {
  isContinues.value = !isContinues.value
  for (var i = 0; i < fileList.value.length; i++) {
    if(fileList.value[i].isuploadFinished==4  ){
        
    }else{
      fileList.value[i].isuploadFinished = 3
    
      fileList.value[i].controller.abort()
    }
    
  }
}
//2.5  继续上传单个文件
const continueUploadingItem = (file, i) => {
  fileList.value[i].isuploadFinished = 1
  // 如果所有的都为继续,则展示 全部暂停
  let flag=false
  for (var j = 0; j < fileList.value.length; j++) {
    if (fileList.value[j].isuploadFinished == 1) {
      flag=true
      break
    }
  }
  // debugger
  if(flag){
     isContinues.value = true
  }
  

  const controller = new AbortController()
  // debugger
  fileList.value[i].controller = controller

  if(fileList.value[i].raw.size<(10*1024*1024)){
     handleFiles(file, i,fileList.value[i].md5,fileList.value[i].totalChunk,)
  }else{
    // debugger
    getChunks(fileList.value[i].minioChunksSecretKey.videoId)
    .then((res)=>{
      
      fileList.value[i].nextPartNumberMarker=res.data.data.nextPartNumberMarker || 0
      handleFiles(file, i,fileList.value[i].md5,fileList.value[i].totalChunk)
    })
    .catch((error)=>{
      
      handleFiles(file, i,fileList.value[i].md5,fileList.value[i].totalChunk)
    })
   
  }
  
}
// 全部继续
const continueUploadingItems = () => {
  isContinues.value = !isContinues.value

  for (var i = 0; i < fileList.value.length; i++) {
    fileList.value[i].isuploadFinished = 1
    
    const controller = new AbortController()
    // debugger
    fileList.value[i].controller = controller
    handleFiles(fileList.value[i], i,fileList.value[i].md5,fileList.value[i].totalChunk)
  }
}

// 折叠按钮
const isFoldValue = ref(true)
const isFold = () => {
  isFoldValue.value = !isFoldValue.value
}

// 2.6 取消上传
const cancelfileList = ref([])
const cancelFileItem = (file, i) => {
  ElMessageBox.confirm('上传尚未完成。要取消所有正在进行的上传吗？', '取消上传', {
    cancelButtonText: '继续上传',
    confirmButtonText: '取消上传',

    type: 'warning'
  })
    .then(() => {
      // debugger
      ElMessage({
        type: 'success',
        message: '取消上传'
      })

      cancelfileList.value.push(fileList.value[i].name)
      //调用取消上传请求
      fileList.value[i].controller.abort()
      // debugger
      fileList.value.splice(i, 1)

      if (fileList.value.length == 0) {
        dialogUploadingVisible.value = false
      }
    })
    .catch(() => {
      ElMessage({
        type: 'success',
        message: '继续上传'
      })
    })
}

// 3. 最近列表
const tableData = ref([
  // {
  // 	"createdTime": "2023年7月1日 下午3:08",  //创建时间
  // 	"currentStatus": 0,  //当前状态,0未下载，1已下载，2已提取图片，3已提取音频，4转录中，5已转录
  // 	"deleteTime": "",
  // 	"exitOss": 0,   //视频上传状态, 0未上传，1已上传
  // 	"fileName": "",  //视频名字
  // 	"flag": 0,  //是否已经在UDS
  // 	"id": 0,   //视频id
  // 	"inputId": "",  //UDS的id
  // 	"isShow": 0,   //是否在主页展示
  // 	"ownby": "",   //归属者
  // 	"picture": "",
  // 	"recentUsedTime": "",  //最近使用时间
  // 	"title": "集团会议集团会议集团会议集团会议集团会议",   //视频标题
  // 	"totalTime": "",   //视频时长
  // 	"transferVideo": 0,   //语义语义转换是否完成
  // 	"url": "",     //视频播放连接
  // 	"userId": "",    //用户工号
  // 	"userName": "张小瑞"    //用户姓名
  //   "recentUsedTime":''
  // }
])
const getRowKeys = (row) => {
  return row.staffTypeId
}

// 轮询刷新--更新转写状态
const setTimeoutZdy = (option) => {
  setTimeout(function () {
    // console.log('轮询')
    // debugger
    try {
      if (typeof option.fn == 'function') {
        option.fn()
        if (option.isClose) {
          return
        }
      }
    } catch {}
    setTimeoutZdy(option)
  }, option.time || 5000)
}
var option = {
  isClose: false,
  fn: () => {
    let total=0
      for(let i=0;i<tableData.value.length;i++){
        let item=tableData.value[i]
        if(item.transferFail==0 && item.transferRate<100){
          total++   
        }
      }
    if(total==0){
      option.isClose=false
    }else{
      request
      .get(
        '/sweet-api/mainpage/' +
          userId.value +
          '?current=' +
          currentPage.value +
          '&pageSize=' +
          pageSize.value
      )
      .then((res) => {
        // debugger
        // console.log("最近列表获取成功",res.data);
        if (res.data.code == 1) {
          // debugger
          for(let j=0;j<res.data.data.length;j++){
            if(tableData.value[j].id==res.data.data[j].id){
              tableData.value[j].transferFail = res.data.data[j].transferFail
              tableData.value[j].transferRate = res.data.data[j].transferRate
              tableData.value[j].picture = res.data.data[j].picture
              tableData.value[j].totalTime = res.data.data[j].totalTime
            }
          }
        }
      })
      .catch((error) => {
        console.log('最近列表获取失败', error)
      })
    }
      
  },
  time: 5000
}


// 3.1 点击图片，跳转到音视频详情页
const goTodetailPage = (row) => {
  // debugger
  if (row.fileName && row.fileName.slice(-3) != 'mp3') {
    router.push({
      path: '/video-page',
      query: {
        id: row.id,
        title: row.title,
        createdTime: row.createdTime,
        totalTime: row.totalTime,
        userName: row.userName,
        url: row.url,
        inputValue: inputValue.value ? inputValue.value : ''
      }
    })
  } else {
    router.push({
      path: '/audio-page',
      query: {
        id: row.id,
        title: row.title,
        createdTime: row.createdTime,
        totalTime: row.totalTime,
        userName: row.userName,
        url: row.url,
        inputValue: inputValue.value ? inputValue.value : ''
      }
    })
  }
}

// 3.2 重命名
// 输入框内容
const renameValue = ref('')
console.log(renameValue.value)
const inputRef = ref('')

const edititem = (row) => {
  row.isShowInput = true
  renameValue.value = row.title
  nextTick(() => {
    // debugger
    inputRef.value.focus()
  })
}
// 输入框失去焦点
const blur = (row) => {
  // debugger
  if(renameValue.value){
     // 隐藏输入框
      row.isShowInput = false

      //调用重命名接口
      resetName(row, renameValue.value)
  }
  
}

// 3.3 单个移除
const deleteitem = (row) => {
  // debugger
  console.log(row.url)

  ElMessageBox.confirm('确定移除当前选中项吗？', '移除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      //调用单个移除请求接口
      delateRecentlyItem([row.id])
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消移除'
      })
    })
}

// 跨页勾选, 删除时选中行
var selectRows = ref([])
const selectionChange = (selection) => {
  selectRows.value = selection
  console.log('33333333333333', selectRows.value)
}

// 3.4 批量移除
const shiftBtns = () => {
  console.log('selectRows.value', selectRows.value)
  let ids = []
  selectRows.value.forEach((item) => {
    ids.push(item.id)
  })
  ElMessageBox.confirm('确定移除当前选中项吗？', '移除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      // 发请求  批量移除接口
      delateRecentlyItem(ids)
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消移除'
      })
    })
}

// 4.分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  //重新发请求，渲染设备列表
  if (inputValue.value != '') {
    getSearchRequest()
  } else {
    getRecentlyContentList()
  }
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)

  //重新发请求，渲染设备列表
  if (inputValue.value != '') {
    getSearchRequest()
  } else {
    getRecentlyContentList()
  }
}
</script>
<style lang="less">
.zdy_upload {
  .imgCont {
    width: 28px;
    height: 28px;
    border-radius: 50%;
    background-color: orange;

    img {
      width: 18px;
      height: 18px;
      margin: 5px;
    }
  }
  .cont {
    color: rgba(16, 16, 16, 1);
    font-size: 16px;
    text-align: left;
    font-family: SourceHanSansSC-regular;
  }
}
</style>
<style lang="less" scoped>
ul li {
  list-style: none;
}
.home {
  margin: 0 ;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  //1.导航栏
  .navigationBar {
    height: 111px;
    border-bottom: 1px solid rgba(239, 239, 239, 1);
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: none;
    .left {
      display: flex;
      justify-content: flex-start;
      .item {
        width: 56px;
        margin-right: 40px;
        display: flex;
        flex-direction: column;
        align-items: center;
       
        & > div:nth-child(1) {
          width: 45px;
          height: 45px;
          border-radius: 4px;
          background-color: rgba(24, 144, 255, 1);
          img {
            width: 25px;
            height: 25px;
            margin: 10px;
          }
        }

        & > div {
          height: 20px;
          font-size: 14px;
          text-align: left;
          font-family: SourceHanSansSC-regular;
          white-space: nowrap;
        }
      }
    }
    .search {
      width: 480px;
      height: 34px;
      border-radius: 2px;
      color: rgba(206, 206, 206, 1);
      font-size: 14px;
      text-align: left;
      font-family: Roboto;
    }
  }
  // 2. 头部
  .top {
    height: 73px;
    border-bottom: 1px solid rgba(239, 239, 239, 1);
    display: flex;
    justify-content: space-between;

    flex: none;
    & > b {
      margin-top: 24px;
    }
    & > div {
      width: 80px;
      height: 32px;
      // line-height: 32px;
      margin-top: 24px;
      border-radius: 2px;

      // 上传文件
      .upload-demo {
        position: relative;
        z-index: 200;
        top: 0px;
      }
    }
  }

  // 3. 会议列表
  .tableBox {
    flex: 1;
    overflow: hidden;
    .recentlyList {
      width: 100%;
      height: 100%;
      padding-top: 14px;
      display: flex;
      flex-wrap: wrap;

      :deep(.el-table) {
        height: 100%;
        .fileContainer {
          display: flex;
          justify-content: flex-start;

          .fileImg {
            width: 160px;
            height: 90px;
            background-color: lightgray;
            border-radius: 4px;
            position: relative;
            margin-right: 20px;
            .img {
              width: 100%;
              height: 100%;
            }
            .defaultImg {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
            }
          }
          .fileInfo {
            // width: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;

            & > div {
              display: flex;

              img {
                width: 18px;
                height: 18px;
                margin-right: 4px;
                margin-top: 3px;
              }
            }

            & > div:nth-child(1) {
              color: rgba(51, 51, 51, 1);
              font-size: 16px;
              text-align: left;
              font-family: SourceHanSansSC-regular;
            }
          }
        }

        //移除按钮
        .cell .el-button:nth-child(2) > span {
          color: red;
        }

        .el-table__header-wrapper thead .cell {
          color: rgba(51, 51, 51, 1);
          border-left: 1px solid rgba(206, 206, 206, 1);
        }
        .el-table__header-wrapper thead th:nth-child(1) .cell {
          border-left: none;
        }
      }
    }
  }

  // 4.分页
  .pagination-block {
    width: 100%;
    height: 52px;
    line-height: 52px;
    // border: 1px solid red;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: none;
    // 分页
    & > div {
      display: flex;
      justify-content: flex-end;
      .el-button {
        width: 48px;
        height: 32px;
        line-height: 32px;
        margin: 10px 10px 10px 8px;
        border-radius: 3px;
        background-color: rgba(79, 168, 249, 1);
        color: rgba(255, 255, 255, 1);
        font-size: 14px;
        text-align: center;
        font-family: Roboto;
      }
    }

    // 移除按钮
    .shiftBtn {
      width: 80px;
      height: 32px;
      line-height: 32px;
      border-radius: 2px;
      // background-color: rgba(255, 77, 79, 1);
      color: rgba(255, 255, 255, 1);
      font-size: 14px;
      text-align: center;
      font-family: Roboto;
      opacity: 0;
    }
    .active {
      opacity: 1;
    }
  }

  // 上传音视频文件弹框
  :deep(.el-dialog) {
    .el-dialog__header {
      margin-right: 0px;
      border-bottom: 1px solid rgba(225, 227, 230, 1);
    }
    .el-dialog__body {
      padding: 20px;
      padding-bottom: 0px;

      .showFileList {
        display: flex;
        flex-direction: column;
        border: 1px solid rgba(194, 199, 204, 1);
        .top1 {
          height: 40px;
          padding-left: 14px;
          padding-right: 14px;
          border-bottom: 1px solid rgba(225, 227, 230, 1);
          display: flex;
          justify-content: space-between;
          align-items: center;
          // 添加按钮
          .tianjia {
            color: rgba(24, 144, 255, 1);
            font-size: 14px;
            text-align: right;
            font-family: SourceHanSansSC-regular;
          }
        }
        .fileList {
          padding: 7px 14px;
          padding-right: 0px;
          margin-left: -42px;

          ul li {
            padding-top: 7px;
            padding-bottom: 7px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            & > div:nth-child(1) {
              display: flex;
              justify-content: space-between;
              align-items: center;
              .name {
                color: rgba(16, 16, 16, 1);
                font-size: 16px;
                text-align: left;
                font-family: SourceHanSansSC-regular;
              }
              .size {
                color: rgba(145, 145, 145, 1);
                font-size: 14px;
                text-align: left;
                font-family: SourceHanSansSC-regular;
              }
            }
            img {
              width: 34px;
              height: 34px;
              margin-right: 10px;
            }
          }
        }
      }
    }
    //上传文件中有 文件列表，则将upload上传框 透明处理
    .el-dialog__body:has(.isShowUpload) {
      .el-upload-dragger {
        position: absolute;
        zoom: 0.2;
        right: 106px;
        top: 424px;
        background-color: transparent;
        opacity: 0;
      }
    }

    .el-dialog__footer {
      .el-button {
        width: 80px;
      }
    }
  }

  //上传中弹框
  :deep(.dialoguploading) {
    width: 400px;
    position: fixed;
    right: 0;
    bottom: -46px;
    .el-dialog__header {
      .title {
        display: flex;
        justify-content: space-between;
        // 折叠按钮
        .isFold {
          width: 22px;
          position: absolute;
          top: 20px;
          right: 46px;
        }
      }
    }

    .el-dialog__body {
      padding: 0px;
      padding-bottom: 0px;

      .showuploadingList {
        display: flex;
        flex-direction: column;

        .top2 {
          height: 40px;
          display: flex;
          background-color: rgba(244, 244, 244, 1);
          justify-content: space-between;
          align-items: center;
          & > div:nth-child(1) {
            margin-left: 20px;
          }
          // 添加按钮
          & > div:nth-child(2) {
            margin-right: 20px;
          }
        }
        .uploadingList {
          padding: 7px 14px;
          padding-right: 0px;
          margin-left: -42px;

          ul {
            li {
              padding-top: 7px;
              padding-bottom: 7px;
              display: flex;
              justify-content: space-between;
              align-items: center;
              & > div:nth-child(1) {
                width: 300px;
                overflow: hidden;

                display: flex;
                justify-content: flex-start;
                align-items: center;
                .name {
                  color: rgba(16, 16, 16, 1);
                  font-size: 16px;
                  text-align: left;
                  font-family: SourceHanSansSC-regular;
                }
                .size {
                  color: rgba(145, 145, 145, 1);
                  font-size: 14px;
                  text-align: left;
                  font-family: SourceHanSansSC-regular;
                }
                img {
                  width: 34px;
                  height: 34px;
                  margin-right: 10px;
                }
              }

              .pauseOrDelBtn {
                display: flex;
                align-items: center;
                margin-right: 6px;
                img {
                  width: 22px;
                  height: 22px;
                  display: none;
                }
                .el-icon svg {
                  display: none;
                }
              }
            }
            :hover {
              // background-color: red;
              .pauseOrDelBtn {
                display: flex;
                align-items: center;
                margin-right: 6px;
                img {
                  display: inline-block;
                }
                .el-icon svg {
                  display: inline-block;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
